<?php

if(!empty($_POST['parents']))
{

   if(!empty($_POST['baner_id']))
       $sql = 'SELECT id,title,parents,br.page_id as br_page_id FROM pages p
               LEFT JOIN baner_relation br ON br.page_id = p.id and br.baner_id='.$_POST['baner_id'].'
               WHERE parents="'.$_POST['parents'].'" ORDER BY title';
   else
      $sql = 'SELECT id,title,parents FROM pages WHERE parents="'.$_POST['parents'].'" ORDER BY title';

   $conn->query($sql);
   if($conn->rowCount())
   {
      $html = '<ul class="sub_category" style="display:none">';
      while($row = $conn->fetch())
      {
         $field_id = 'select_page_'.$row->id;
          $parents = $row->parents.'#'.$row->id.'#';

          $checked = '';

          if(isset($_POST['checked']))
            $checked = 'checked="cheked"';
         elseif(property_exists($row,'br_page_id'))
            if($row->br_page_id > 0)
               $checked = 'checked="cheked"';

          $html .= '
          <li _parents="'.$parents.'">
            <input type="checkbox" '.$checked.' name="pages[]" value="'.$row->id.'">
            <label><span>'.$row->title.'</span></label>
          </li>';
      }
      $html .='</ul>';
      die($html);
   }
   else die();
}
